package progetto1.csm.implementation;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import progetto1.csm.core.AbstractStatistics;
import progetto1.csm.core.DataBuilder;
import progetto1.csm.core.StatisticType;
import progetto1.csm.core.Statistics;
import progetto1.csm.core.SystemElement;

public class CSVFileBuilder implements DataBuilder {
	
	private File file;
	private Writer writer;
	private CSVPrinter printer;
	private boolean created = false;
	private static final char DEL = ';';
	private static final String FORMAT = "%.7f";
	
	private StatisticType[] types;
	private SystemElement[] elements;
	
	public CSVFileBuilder(String filePath) {
		inizialize(filePath);
	}

	@Override
	public void build(Statistics s) {
		try {
			if (created) {
				if (s instanceof AbstractStatistics) {
					AbstractStatistics as = (AbstractStatistics) s;
					types = as.getStatisticsTypes();
					elements = as.getSystemElements();
				} else {
					assert false;
				}
				secondInizialize();
			}
			printer.print(s.getNumClient());
			for (int j = 0; j < elements.length; j++) {
				for (int i = 0; i < types.length; i++) {
					printer.print(format(s.getValue(types[i], elements[j])));
				}
			}
			printer.flush();
			printer.println();
		} catch (IOException e) {
			catching(e);
		}
	}

	
	@Override
	public Object getInstance() {
		try{
			printer.flush();
			writer.flush();
			printer.close();
			writer.close();
		}catch(IOException e){
			catching(e);
		}
		return null;
	}

	private void inizialize(String filePath) {
		try{
			file = new File(filePath);
			if(!file.exists()){
				file.createNewFile();
			}
			writer = new FileWriter(file);
			printer = new CSVPrinter(writer, CSVFormat.EXCEL.withDelimiter(DEL));
			created = true;
		}catch(IOException e){
			catching(e);
		}
	}

	private void catching(IOException e) {
		System.out.println("Impossibile operare sul disco");
		e.printStackTrace();
		System.exit(-1);
	}
	
	private void secondInizialize() throws IOException {
		printer.print("K");
		for (int j = 0; j < elements.length; j++) {
			for (int i = 0; i < types.length; i++) {
				printer.print(types[i].toString()+"("+elements[j].toString()+")");
			}
		}
		printer.println();
		created = false;
	}	
	
	private String format(double value) {
		return String.format(FORMAT, value);
	}

}
